package com.cqndt.disaster.device.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * 北京速达短信平台短信发送工具类
 * @author rxj created by 2017/11/30
 */
public class SudasSmsUtil {
    /** 短信接口地址 */
    private static final String URL = "http://sdk8.interface.sudas.cn/z_mdsmssend.php";
    /** 用户的账号，由服务商提供 */
    private static final String SN= "SUD-KEY-010-00455";
    /** 用户的密码，将服务商提供的明码通过MD5加密得到32位长度字符串。必须大写。 */
    private static final String PWD= "566F7F1BF7E8364A089778691069BBAD";
    /** 扩展码 */
    private static final String EXT= "";
    /** 唯一标识 */
    private static final String RRID= "";
    /** 参数必须提交，值可为空。值为空表示立即发送。参数格式2011-8-22 13:37:35 */
    private static final String STIME= "";
    /** 默认接口参数值为1 */
    private static final String STYPE= "1";
    /** 启用则配合MD5key密钥对内容进行加密)。1表示启用。2表示禁用。 */
    private static final String SSAFE= "2";
    /** 短信内容编码格式(1表示UTF-8，2表示GB2312) */
    private static final String SCODE= "1";
    /** ssafe启用时必填。配置Md5Sign参数时，MD5加密使用 */
    private static final String MD5_KEY= "nearloing123";
    /** 用作调试接口。参数值为1时表示接口调试，只记录提交数据，返回提交结果（此结果与正式发送结果返回值一致）。正式提交不用配置此参数 */
    private static final String DEBUG = "0";
    /** 支持SSL传输加密(1是 2否) */
    private static final String SSL = "2";
    /** 如果启用ssafe，此参数值为将接口其他参数按照要求通过MD5加密得到的32位字符串。加密顺序：MD5(sn|pwd|mobile|content|ext|rrid|stime|stype|ssafe|scode|md5key) */
    private static final String MD5_SIGN = "";

    /**
     * 私有化构造函数
     */
    private SudasSmsUtil(){}

    /**
     * 短信发送
     * @param mobile 手机号码,多个手机号通过英文逗号隔开
     * @param content 短信内容+签名
     */
    public static void send(String mobile, String content){
        // 创建httpclient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建http post请求
        HttpPost httpPost = new HttpPost(URL);
        // 配置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                //设置连接超时时间
                .setConnectTimeout(10000)
                // 设置连接请求最长时间
                .setConnectionRequestTimeout(10000)
                //数据传输的最长时间
                .setSocketTimeout(10000)
                .setRedirectsEnabled(true)
                .build();
        httpPost.setConfig(requestConfig);
        //http post请求参数构建
        List<BasicNameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("sn", SN));
        nvps.add(new BasicNameValuePair("pwd", PWD));
        nvps.add(new BasicNameValuePair("mobile", mobile));
        nvps.add(new BasicNameValuePair("content", content+"【云南省地调局】"));
        nvps.add(new BasicNameValuePair("ext", EXT));
        nvps.add(new BasicNameValuePair("rrid", RRID));
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("stype", STYPE));
        nvps.add(new BasicNameValuePair("ssafe", SSAFE));
        nvps.add(new BasicNameValuePair("scode", SCODE));
        nvps.add(new BasicNameValuePair("MD5key", MD5_KEY));
        nvps.add(new BasicNameValuePair("debug", DEBUG));
        nvps.add(new BasicNameValuePair("ssl", SSL));
        nvps.add(new BasicNameValuePair("Md5Sign", MD5_SIGN));
        try {
            //http post参数设置
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        CloseableHttpResponse response=null;
        try {
            // 执行http post请求
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();// 获取返回实体
            // 处理响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
                String result = EntityUtils.toString(entity, "UTF-8");
                System.out.println(result);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(response!=null){
                try {
                    response.close();//关闭流和释放资源
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpClient!=null){
                try {
                    httpClient.close();// 关闭httpclient
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) throws ClientProtocolException, IOException {
        send("13987669710","祝传兵主任,你好。云南省红河县莲花家园小区地质灾害专业监测点监测:GNSS监测设备,触发相邻告警,设备编号为:YNLH01_GNSS,本次监测和上次监测值为:1.1,监测时间:2019-07-10 05:30:00,请尽快进行何查处理");
        send("13619691123","周翠琼,你好。云南省红河县莲花家园小区地质灾害专业监测点监测:GNSS监测设备,触发相邻告警,设备编号为:YNLH01_GNSS,本次监测和上次监测变化值为:1.1,监测时间:2019-07-10 05:30:00,请尽快进行何查处理");
//        send("13594170706","尹清钦,你好。云南省红河县莲花家园小区地质灾害专业监测点监测:GNSS监测设备,触发累计告警,设备编号为:YNLH01_GNSS,本次监测值为:21.8,监测时间:2019-07-10 06:06:00,请尽快进行何查处理");
    }

    /**
     * MD5加密
     * @param sourceStr 带加密字符串
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getMD5(String sourceStr) throws UnsupportedEncodingException {
        String resultStr = "";
        try {
            byte[] temp = sourceStr.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(temp);
            // resultStr = new String(md5.digest());
            byte[] b = md5.digest();
            for (int i = 0; i < b.length; i++) {
                char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                        '9', 'A', 'B', 'C', 'D', 'E', 'F' };
                char[] ob = new char[2];
                ob[0] = digit[(b[i] >>> 4) & 0X0F];
                ob[1] = digit[b[i] & 0X0F];
                resultStr += new String(ob);
            }
            return resultStr;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
